#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>

int get_temperature(float *temp);
int main(int argc,char *argv[]) 
{
        float             temp;
        int               rv;
        rv=get_temperature(&temp);
        if(rv<0)
        {
        printf("get temperature failure,return value:%d",rv);
        return -1;
        }
        printf("temp:%f\n",temp);
}
int get_temperature(float *temp)
{
	int               fd = -1;
	char              buf[128];
	char              *ptr = NULL;
	DIR               *dirp = NULL;
	struct dirent     *direntp = NULL;
	char              w1_path[64]="/sys/bus/w1/devices/";
	char              chip_sn[32];
	char              ds18b20_path[64];
	int               found = 0;

	dirp = opendir(w1_path);
	if(!dirp)
	{
		printf("open folder %s failure:%s\n",w1_path,strerror(errno));
		return -1;
	}

	while(NULL !=(direntp=readdir(dirp)))
	{
		if(strstr(direntp->d_name,"28-"))
		{
			strncpy(chip_sn,direntp->d_name,sizeof(chip_sn));
			found = 1;

		}
		printf("filename:%s\n",direntp->d_name);
	
	}

	closedir(dirp);

	if(!found)
	{
		printf("Can not find ds18b20 chipset\n");
		return -1;
	}

	strncat(w1_path,chip_sn,sizeof(w1_path)-strlen(w1_path));
	strncat(w1_path,"/w1_slave",sizeof(w1_path)-strlen(w1_path));
	printf("w1_path:%s\n",w1_path);

	fd = open(w1_path,O_RDONLY);
	
	if(fd<0)
	{
		printf("open file failure:%s\n",strerror(errno));
		return -1;
	}
	memset(buf,0,sizeof(buf));

	if(read(fd,buf,sizeof(buf))<0)
	{
		printf("read data from fd=%s failure:%s\n",fd,strerror(errno));
		return -1;
	}
	printf("buf:%s\n",buf);
	ptr=strstr(buf,"t=");

	if(!ptr)
	{
		printf("Can not find t= string\n");

	close(fd);
		return -1;
	}
	ptr +=2;
	*temp=atof(ptr)/1000;
	printf("temprature:%f\n",*temp);

	close(fd);

}
